import LocalCache from "@/utils/storage";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import axios, {
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";

const service = axios.create({
  timeout: 6000,
  baseURL: import.meta.env.VITE_API_BASEURL,
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    config.headers.set("token", LocalCache.get("token"));
    return config as InternalAxiosRequestConfig;
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const router = useRouter();
    if (response.status !== 200) {
      return Promise.reject(response);
    }
    const { data } = response;
    // return data;
    switch (data.code) {
      case 0: //判断后端内部返回code值为0
        // Message.success("操作成功");
        return data;
      case 1:
        Message.error(data.msg || "服务器内部错误");
        return Promise.reject(response);
      case 2:
        if (data.msg === "登录失效") Message.error(data.msg);
        LocalCache.clear(); // 清除浏览器全部临时缓存
        router.push("/login");
      // return Promise.reject(response);
      default:
        return Promise.reject(response);
    }
  },
  (err) => {
    const router = useRouter();
    switch (err.response.status) {
      case 401:
        err.message = "登录已失效，请重新登录";
        LocalCache.clear(); // 清除浏览器全部临时缓存
        router.push("/login");
        // ElMessageBox.alert("你已被登出，请重新登录", "提示", {});
        break;
      case 404:
        err.message = `请求地址出错: ${err.response.config.baseURL}${err.response.config.url}`;
        break;
      case 500:
        err.message = "服务器内部错误";
      default:
        err.message = "网关错误";
        break;
    }
    Message.error(err.message);
  }
);

export default service;
